package com.tmall.wireless.virtualviewdemo.provider;

import com.tmall.wireless.vaf.Log;
import com.tmall.wireless.virtualviewdemo.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

public class MainListAdapter extends BaseItemProvider {

    private List<MainItemEntity> data;

    private LayoutScatter layoutScatter;

//    private Context mContext;

    public MainListAdapter(Context context, List<MainItemEntity> data) {
//        this.mContext = context;
        this.data = data;
        Log.i("MainListAdapter.MainListAdapter([context, data]):22  " + data.size());
        this.layoutScatter = LayoutScatter.getInstance(context);
    }

    @Override
    public int getCount() {
        int count = data != null ? data.size() : 0;
        Log.i("MainListAdapter.getCount([]):27    " + count);
        return count;
    }

    @Override
    public Object getItem(int i) {
        return data == null || data.isEmpty() ? null : data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void setNewData(List<MainItemEntity> list) {
        if (list == null) {
            return;
        }
        if (data == null) {
            data = new ArrayList<>();
        }
        data.clear();
        data.addAll(list);
        notifyDataChanged();
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {

        ViewHolder viewHolder = null;
        if (component == null) {
            component = layoutScatter.parse(ResourceTable.Layout_item_main_list, null, false);
            viewHolder = new ViewHolder((ComponentContainer) component);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) component.getTag();
        }
        MainItemEntity mainItemEntity = data.get(i);
        viewHolder.tvItemTitle.setText(mainItemEntity.name);
        viewHolder.tvItemStyle.setText(mainItemEntity.desp);
        return component;
    }

    static class ViewHolder {

        Text tvItemTitle;
        Text tvItemStyle;

        public ViewHolder(ComponentContainer componentContainer) {
            tvItemTitle = (Text) componentContainer.findComponentById(ResourceTable.Id_tv_title);
            tvItemStyle = (Text) componentContainer.findComponentById(ResourceTable.Id_tv_style);
        }
    }

    public static class MainItemEntity {
        public String name;
        public String data;
        public String clasz;
        public String desp;

        @Override
        public String toString() {
            return "MainItemEntity{" +
                    "name='" + name + '\'' +
                    ", date='" + data + '\'' +
                    ", clasz='" + clasz + '\'' +
                    '}';
        }
    }
}